import Quill from 'quill';
const BlockEmbed = Quill.import('blots/block/embed');

// 定义图片 Blot 类型
class ImageBlot extends BlockEmbed {
  static create(value) {
    let node = super.create(value);
    node.setAttribute('src', value.url);
    return node;
  }

  static value(node) {
    return { url: node.getAttribute('src') };
  }
}

ImageBlot.blotName = 'image';
ImageBlot.tagName = 'IMG';

// 定义视频 Blot 类型
class VideoBlot extends BlockEmbed {
  static create(value) {
    let node = super.create(value);
    const videoElement = document.createElement('video');
    videoElement.src = value.url;
    videoElement.controls = true;
    videoElement.style.maxWidth = '100%'; // 确保视频适应编辑器宽度
    node.appendChild(videoElement);
    return node;
  }

  static value(node) {
    const videoElement = node.querySelector('video');
    return { url: videoElement.src };
  }
}

VideoBlot.blotName = 'video';
VideoBlot.tagName = 'DIV';

Quill.register({
  'formats/image': ImageBlot,
  'formats/video': VideoBlot
});

// 定义文件上传模块
function FileUpload(quill, options) {
  this.quill = quill;
  this.options = options;

  // 添加图片和视频按钮到工具栏
  const toolbar = quill.getModule('toolbar');
  toolbar.addHandler('image', this.showImageUploader.bind(this));
  toolbar.addHandler('video', this.showVideoUploader.bind(this));

  // 创建并配置文件输入元素
  this.fileInput = document.createElement('input');
  this.fileInput.setAttribute('type', 'file');
  this.fileInput.addEventListener('change', this.uploadFile.bind(this));
  this.fileInput.style.display = 'none';
  document.body.appendChild(this.fileInput);
}

FileUpload.prototype.showImageUploader = function () {
  this.fileInput.setAttribute('accept', 'image/*');
  this.fileInput.click();
};

FileUpload.prototype.showVideoUploader = function () {
  this.fileInput.setAttribute('accept', 'video/*');
  this.fileInput.click();
};

FileUpload.prototype.uploadFile = async function (event) {
  const file = event.target.files[0];
  if (!file) return;

  try {
    const formData = new FormData();
    formData.append('file', file);

    // 这里应该替换为你的服务器端点和请求方法
    const response = await fetch('/upload-file-endpoint', {
      method: 'POST',
      body: formData,
      headers: {
        // 如果需要身份验证或其它头部信息，请在此添加
      }
    });

    if (response.ok) {
      const result = await response.json();
      console.log('File upload successful:', result); // 调试信息
      const range = this.quill.getSelection(true);
      const embedType = file.type.startsWith('image/') ? 'image' : 'video';
      this.quill.insertEmbed(range.index, embedType, result.url, Quill.sources.USER);
      this.quill.setSelection(range.index + 1);
    } else {
      console.error('Failed to upload file. Server responded with:', response.statusText);
    }
  } catch (error) {
    console.error('Error during file upload:', error.message);
  } finally {
    this.fileInput.value = ''; // 清空文件选择框
  }
};

export default FileUpload;